package js.web.center.script.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
/**
 * 脚本执行工具
 * @author dowell
 *
 */

import org.apache.log4j.Logger;

import js.web.center.script.core.JsWebScriptEngineCore;
public class JsWebScriptUtils {
	private static Logger logger=Logger.getLogger(JsWebScriptUtils.class);
	public static int scriptIds=1;
	private static JsWebScriptUtils scriptUtils=null;
	private HashMap<Integer, JsWebScriptEngineCore> hashMap=new HashMap<>();
	public static JsWebScriptUtils getInstance(){
		if(scriptUtils==null){
			scriptUtils=new JsWebScriptUtils();
		}
		return scriptUtils;
	}
	public void logInfo(String info){
		logger.info(info);
	}
	public void logWarn(String info){
		logger.warn(info);
	}
	public void logError(String info){
		logger.error(info);
	}
	/**
	 * 添加脚本文件到自动管理器
	 * @param id 文件id
	 * @param sc 脚本执行器
	 */
	public synchronized void addScriptEngineCore(int id,JsWebScriptEngineCore sc){
		hashMap.put(id, sc);
	}
	/**
	 * 获取所有脚本信息
	 * @return
	 */
	public ArrayList<JsWebScriptEngineCore> getScriptEngineCores(){
		Collection<JsWebScriptEngineCore> values = hashMap.values();
		ArrayList<JsWebScriptEngineCore> arrayList=new ArrayList<>(values);
		return arrayList;
	}
	/**
	 * 刷新脚本文件
	 */
	public synchronized void refreshScriptEngineCore(){
		try{
			Set<Entry<Integer,JsWebScriptEngineCore>> entrySet = hashMap.entrySet();
			ArrayList<Integer> arrayList=new ArrayList<>();
			for (Entry<Integer, JsWebScriptEngineCore> entry : entrySet) {
				if(!entry.getValue().isDestory()){
					entry.getValue().refresh();
				}else{
					arrayList.add(entry.getKey());
				}
			}
			for (Integer key : arrayList) {
				hashMap.remove(key);
			}
		}catch(Exception e){
			logger.error("JsWebScriptUtils ERROR:{}",e);
		}
	}
}
